package gitee.wakyde.remoting.transport.netty.codec;

import gitee.wakyde.serialize.Serialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 自定义解码器
 */
@AllArgsConstructor
@Slf4j
public class NettyKryoDecoder extends ByteToMessageDecoder {
    private final Serialize serialize;
    private final Class<?> genericClass;

    private static final int BODY_LENGTH = 4;

    /**
     * 解码ByteBuff对象
     * @param channelHandlerContext
     * @param byteBuf
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(byteBuf.readableBytes() >= BODY_LENGTH){
            byteBuf.markReaderIndex();
            int length = byteBuf.readInt();
            if(length < 0 || byteBuf.readableBytes() < 0){
                log.error("data length or byteBuf readableBytes is not valid");
                return;
            }
            if(byteBuf.readableBytes() < length){
                byteBuf.resetReaderIndex();
                return;
            }
            byte[] bytes = new byte[length];
            byteBuf.readBytes(bytes);
            Object deserialize = serialize.deserialize(bytes, genericClass);
            list.add(deserialize);
            log.info("Successful decode ByteBuf to Object");
        }
    }


}
